package com.sanjiahantang.ythshopping.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.sanjiahantang.ythshopping.R;
import com.sanjiahantang.ythshopping.activity.me.SelectAreaActivity;

import com.sanjiahantang.ythshopping.model.Area;
import com.sanjiahantang.ythshopping.model.NearbyShop;
import com.sanjiahantang.ythshopping.model.NearbyShopModel;
import com.sanjiahantang.ythshopping.presenter.NearbyShopPresenter;
import com.sanjiahantang.ythshopping.views.NearbyShopView;
import com.sanjiahantang.shopping.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.shopping.uilibrary.adapter.listview.QuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class NearbyShopSearchActivity extends BaseActivity implements View.OnClickListener,
        NearbyShopView, AMapLocationListener, AdapterView.OnItemClickListener {

    TextView title;
    FrameLayout back;
    ListView menuList;
    QuickAdapter<NearbyShop.CatList> adapter;
    NearbyShopPresenter presenter;
    SwipeRefreshLayout refreshLayout;
    RecyclerView shopList;

    private LinearLayoutManager linearManager;
    private List<NearbyShop.ShopList> datas;
    private LinearLayout mainContents;

    public AMapLocationClient client = null;
    private AMapLocationClientOption locationOption;
    private double longitude;
    private double latitude;

    private Button select;

    private String province = "";
    private String city = "";
    private String district = "";
    private String cat_id = "";
    private Map<String, String> param = new HashMap<>();
    private int page = 1;
    private int currentPosition;

    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.nearby_search_layout);
        menuList = (ListView) findViewById(R.id.lvOneLevel);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh);
        select = (Button) findViewById(R.id.select_area);
        shopList = (RecyclerView) findViewById(R.id.nearby_shop_list);
        select.setOnClickListener(this);
        linearManager = new LinearLayoutManager(this);
        shopList.setLayoutManager(linearManager);
        mainContents = (LinearLayout) findViewById(R.id.contents);
        shopList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                boolean isBottom = shopList.canScrollVertically(1);
                if (isBottom){
                    page ++;
                    initParam();
                    presenter.getNearbyShopList(NearbyShopSearchActivity.this, param);
                }
            }
        });
        adapter = new QuickAdapter<NearbyShop.CatList>(this, R.layout.category_one_level_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, NearbyShop.CatList item) {
                if (item.isChecked()) {
                    helper.getView(R.id.ivRightLine).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.ivRightLine).setVisibility(View.GONE);

                }
                helper.getView(R.id.tvOneLevelName).setSelected(item.isChecked());
                helper.setText(R.id.tvOneLevelName, item.getCat_name());
            }
        };
        menuList.setAdapter(adapter);
        menuList.setOnItemClickListener(this);


        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                initParam();
                presenter.getNearbyShopList(NearbyShopSearchActivity.this, param);
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        client = new AMapLocationClient(getApplicationContext());
        client.setLocationListener(this);
        presenter = new NearbyShopPresenter(this);
        locationOption = new AMapLocationClientOption();
        locationOption.setOnceLocation(true);
        locationOption.setOnceLocationLatest(true);
        client.setLocationOption(locationOption);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        } else {
            refreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(true);
                }
            });
            client.startLocation();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                refreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(true);
                    }
                });
                client.startLocation();
            } else {
                showToast("未授予权限，无法进行定位服务！");
            }
        }
    }

    @Override
    public void initTitle() {
        super.initTitle();
        title = (TextView) findViewById(R.id.title);
        back = (FrameLayout) findViewById(R.id.fl_Left);
        title.setText("附近商家");
        back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_Left:
                finish();
                break;
            case R.id.select_area:
                if (datas != null){
                    datas.clear();

                }
                Intent it = new Intent(mContext, SelectAreaActivity.class);
                startActivityForResult(it, 1);
                break;
        }
    }

    @Override
    public void getNearbyShop(NearbyShopModel model) {
        refreshLayout.setRefreshing(false);
        if (model.getCode().equals("1")) {
            adapter.clear();
            adapter.addAll(model.getData().getCat_list());
            adapter.getItem(currentPosition).setChecked(true);
            mainContents.setVisibility(View.VISIBLE);
            cat_id = adapter.getItem(currentPosition).getCat_id();
        }
    }

    @Override
    public void getNearbyShopList(NearbyShopModel model) {
        refreshLayout.setRefreshing(false);
        if (model.getCode().equals("1")) {
            datas = model.getData().getShop_list();

        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                longitude = aMapLocation.getLongitude();
                latitude = aMapLocation.getLatitude();
                presenter.getNearbyShopList(this, longitude, latitude);
                initParam();
                presenter.getNearbyShopList(this, param);
            }
        }
    }

    private void initParam() {
        param.put("page", String.valueOf(page));
        param.put("lng", String.valueOf(longitude));
        param.put("lat", String.valueOf(latitude));
        param.put("cat_id", cat_id);
        param.put("province", province);
        param.put("city", city);
        param.put("district", district);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (currentPosition == position) return;

        page = 1;
        if (datas != null) {
            datas.clear();

        }
        adapter.getItem(currentPosition).setChecked(false);
        adapter.getItem(position).setChecked(true);
        adapter.notifyDataSetChanged();
        cat_id = adapter.getItem(position).getCat_id();
        if (android.os.Build.VERSION.SDK_INT >= 11) {

            menuList.smoothScrollToPositionFromTop(position, 0);
        } else {
            menuList.setSelectionFromTop(position, 0);
        }
        currentPosition = position;
        initParam();
        presenter.getNearbyShopList(this, param);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null) {
            return;
        }
        Bundle b = data.getExtras();
        ArrayList<Area> list = (ArrayList<Area>) b.getSerializable("arealist");
        if (list.size() == 3) {
            province = list.get(0).getRegion_id();
            city = list.get(1).getRegion_id();
            district = list.get(2).getRegion_id();
            initParam();
            presenter.getNearbyShopList(this, param);
            String address = "";
            if (list.get(0).getRegion_name().equals(list.get(1).getRegion_name())){
                address = list.get(0).getRegion_name() + list.get(2).getRegion_name();
            }else address = list.get(0).getRegion_name() + list.get(1).getRegion_name() + list.get(2).getRegion_name();
            select.setText(address);
        }
    }
}
